package app.vendorportal.util;

import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.AbstractView;

/**
 * @author Soldier.Xu
 *
 */
public class ViewCSV extends AbstractView {

    @SuppressWarnings("unchecked")
    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment; filename=" + model.get("fileName") + ".csv");
        PrintWriter pw = response.getWriter();
        StringBuffer title = new StringBuffer();
        StringBuffer data = new StringBuffer();
        try {
            List<Object> list = (List<Object>) model.get("dataList");
            for (int i = 0; i < list.size(); i++) {
                LinkedHashMap<String, Object> mapdata = (LinkedHashMap<String, Object>) list.get(i);
                for (Map.Entry<String, Object> entry : mapdata.entrySet()) {
                    if (i == 0) {
                        title.append(entry.getKey()).append(',');
                    }
                    data.append(entry.getValue()).append(',');
                }
                data.append("\t\n");
            }
            pw.write(title.append("\t\n").toString());
            pw.write(data.toString());
            pw.flush();
            pw.close();
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }

    }

}
